#include "myview.h"
#include "mainapp.h"

myWebView::myWebView(QWidget* parent)
    : QWebView(parent)
{
}

MainWindow *myWebView::mainWindow()
{
    QObject *w = this->parent();
    while (w) {
        if (MainWindow *mw = qobject_cast<MainWindow*>(w))
            return mw;
        w = w->parent();
    }
    //return MainWindow::instance()->mainWindow();

//QAction x=pageAction(QWebPage::DownloadLinkToDisk);
//pageAction(QWebPage::DownloadLinkToDisk)->trigger();

connect(pageAction(QWebPage::DownloadLinkToDisk), SIGNAL(triggered(bool)), this, SLOT(openLinkInNewTab(bool)));

}


void myWebView::contextMenuEvent(QContextMenuEvent *event)
{
    QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos());
    if (!r.linkUrl().isEmpty()) {
link=r.linkUrl();
        QMenu menu(this);
        menu.addAction(pageAction(QWebPage::OpenLinkInNewWindow));
        menu.addAction(tr("Open in New Tab"), this, SLOT(openLinkInNewTab()));
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        menu.addAction(tr("Save link into *URIEL* folder"), this, SLOT(saveLinkIntoFolder()));
        menu.addAction(tr("URIEL IS BRITE"), this, SLOT(saveLinkIntoFolder()));
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        // Add link to bookmarks...
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::CopyLinkToClipboard));
        if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled))
            menu.addAction(pageAction(QWebPage::InspectElement));
        menu.exec(mapToGlobal(event->pos()));
        return;
    }
    QWebView::contextMenuEvent(event);
}

///////////////////////////////////////////////////////////////////////////////////////
void myWebView::httpRequestFinished(int requestId, bool error)
 {
     if (requestId != httpGetId)
         return;
     if (httpRequestAborted) {
         if (file) {
             file->close();
             file->remove();
             delete file;
             file = 0;
         }
         progressDialog->hide();
         return;
     }
     if (requestId != httpGetId)
         return;
     progressDialog->hide();
     file->close();
     if (error) {
         file->remove();
         QMessageBox::information(this, tr("HTTP"),
                                  tr("Download failed: %1.")
                                  .arg(http->errorString()));
     } else {
         QString fileName = QFileInfo(QUrl(payload).path()).fileName();
         //statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
     }
     delete file;
     file = 0;
 }
///////////////////////////////////////////////////////////////////////////////////////
 void myWebView::readResponseHeader(const QHttpResponseHeader &responseHeader)
 {
     switch (responseHeader.statusCode()) {
     case 200:                   // Ok
     case 301:                   // Moved Permanently
     case 302:                   // Found
     case 303:                   // See Other
     case 307:                   // Temporary Redirect
         // these are not error conditions
         break;
     default:
         QMessageBox::information(this, tr("HTTP"),
                                  tr("Download failed: %1.")
                                  .arg(responseHeader.reasonPhrase()));
         httpRequestAborted = true;
         progressDialog->hide();
         http->abort();
     }
 }
///////////////////////////////////////////////////////////////////////////////////////
void myWebView::cancelDownload()
{
     //statusLabel->setText(tr("Download canceled."));
     httpRequestAborted = true;
     http->abort();
     //downloadButton->setEnabled(true);
 }
///////////////////////////////////////////////////////////////////////////////////////
void myWebView::updateDataReadProgress(int bytesRead, int totalBytes)
 {
     if (httpRequestAborted)
         return;
     progressDialog->setMaximum(totalBytes);
     progressDialog->setValue(bytesRead);
 }
///////////////////////////////////////////////////////////////////////////////////////

void myWebView::saveLinkIntoFolder()
{
    pageAction(QWebPage::DownloadLinkToDisk)->trigger();

    QMessageBox msgBox;
    msgBox.setText("The document has been modified.");
//    msgBox.exec();


//void HttpWindow::downloadFile()
///////////////////////////////////////////////////////////////////////////////////////
     progressDialog = new QProgressDialog(this);
     connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
     http = new QHttp(this);
     payload="http://media.pimco-global.com/audio/Investment_Outlook_Podcast_05_09.mp3?WT.cg_n=PIMCO-US&WT.ti=Investment_Outlook_Podcast_05_09.mp3";
     payload=link;
     QUrl url(payload);
     QFileInfo fileInfo(url.path());
     QString fileName = fileInfo.fileName();
     if (fileName.isEmpty())
         fileName = "index.html";

     if (QFile::exists(fileName)) {
         if (QMessageBox::question(this, tr("HTTP"),
                                   tr("There already exists a file called %1 in "
                                      "the current directory. Overwrite?").arg(fileName),
                                   QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Cancel)
             == QMessageBox::Cancel)
             return;
         QFile::remove(fileName);
     }

     file = new QFile(fileName);

     connect(http, SIGNAL(requestFinished(int, bool)), this, SLOT(httpRequestFinished(int, bool)));
     connect(http, SIGNAL(dataReadProgress(int, int)), this, SLOT(updateDataReadProgress(int, int)));
     connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)), this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
     connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));

    if (!file->open(QIODevice::WriteOnly)) {
         QMessageBox::information(this, tr("HTTP"),
                                  tr("Unable to save the file %1: %2.")
                                  .arg(fileName).arg(file->errorString()));
         delete file;
         file = 0;
         return;
     }

    QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
    http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port());

    if (!url.userName().isEmpty())
         http->setUser(url.userName(), url.password());

     httpRequestAborted = false;

    QByteArray path = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
     if (path.isEmpty())
         path = "/";
     httpGetId = http->get(path, file);

     progressDialog->setWindowTitle(tr("HTTP"));
     progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
///////////////////////////////////////////////////////////////////////////////////////


/*
///////////////////////////////////////////////////////////////////////////////////////
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
//manager->get(QNetworkRequest(QUrl("http://qtsoftware.com")));
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
QNetworkRequest request;
request.setUrl(QUrl("http://qtsoftware.com"));
request.setRawHeader("User-Agent", "Medusa 1.0");
QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),this, SLOT(slotSslErrors(QList<QSslError>)));
///////////////////////////////////////////////////////////////////////////////////////
*/





//q = new QUrl("http://media.pimco-global.com/audio/Investment_Outlook_Podcast_05_09.mp3?WT.cg_n=PIMCO-US&WT.ti=Investment_Outlook_Podcast_05_09.mp3");
//qnr = new QNetworkRequest(&q);
//download(qnr,true);


}


void myWebView::download(const QNetworkRequest &request, bool requestFileName)
{
//    m_page->m_openInNewTab = true;
//    pageAction(QWebPage::OpenLinkInNewWindow)->trigger();
    QMessageBox msgBox;
    msgBox.setText("HERE IN DOWN LOAD ZONE");
    msgBox.exec();
}






void myWebView::openLinkInNewTab(bool b)
{
//    m_page->m_openInNewTab = true;
//    pageAction(QWebPage::OpenLinkInNewWindow)->trigger();
    QMessageBox msgBox;
    msgBox.setText("The document has been modified.");
    msgBox.exec();
}


QWebView *myWebView::createWindow(QWebPage::WebWindowType type)
//QWebPage *myWebView::createWindow(QWebPage::WebWindowType type)
{
//*
 QMessageBox msgBox;
 msgBox.setText("The document has been modified.");
 //msgBox.exec();
//*/

//MainWindow *mainWindow =
//MainWindow::instance()-> *mainWindow =

        //return mainWindow()->finestra->page();

//*
    Q_UNUSED(type);
/*
    if (m_keyboardModifiers & Qt::ControlModifier || m_pressedButtons == Qt::MidButton)
        m_openInNewTab = true;
    if (m_openInNewTab) {
        m_openInNewTab = false;
// OPEN NEW TAB //
        return mainWindow()->tabWidget()->newTab()->page();
    }
*/


    //return mainWindow()->tWidget()->newTab();//->page();    // OK POPUP IN NEW TAB
    return mainWindow()->tWidget()->currentWebView();         // OK POPUP IN SAME TAB


// HERE WE ARE //
// OPEN NEW WINDOW //

    //return mainWindow()->tWidget()->page();
    mainApplication::instance()->newMainWindow();
    MainWindow *mainWindow = mainApplication::instance()->mainWindow();
    //return//
//    mainWindow->showMaximized();
    mainWindow->setWindowTitle("POPPAMEDUSA");
//    return mainWindow->tWidget()->newTab();//->page(); // OK BUT 1 TAB IN EXCESS > FORGET IT

//    return mainWindow->currentTab();//->page(); // OK POPUP IN NEW WINDOW

//*/
}
